package com.jlcloud.core.log.filter;

import com.jlcloud.core.log.utils.LogTraceUtil;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import net.logstash.logback.encoder.org.apache.commons.lang3.StringUtils;

import java.io.IOException;

/**
 * 日志追踪过滤器
 *
 * @author By: JlCloud <br>
 * @Package: com.jlcloud <br>
 * @CreateTime: 2024-12-03 21:45 <br>
 * @Copyright: 2021 www.jilianjituan.com Inc. All rights reserved. <br>
 * @Caution 注意：本内容仅限于冀联人力集团内部传阅，禁止外泄以及用于其他的商业目的 <br>
 */
public class LogTraceFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		boolean flag = Boolean.FALSE;
		String traceId = null;
		if (request instanceof HttpServletRequest) {
			//从上游服务获取traceId
			traceId = ((HttpServletRequest) request).getHeader(LogTraceUtil.UNIQUE_ID);
		}
		if (StringUtils.isBlank(traceId)) {
			flag = LogTraceUtil.insert();
		} else {
			flag = LogTraceUtil.insert(traceId);
		}
		try {
			chain.doFilter(request, response);
		} finally {
			if (flag) {
				LogTraceUtil.remove();
			}
		}
	}

	@Override
	public void destroy() {
	}

}
